package com.sqx.modules.health.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.sqx.common.utils.RedisUtils;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.config.RemoteConfig;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.service.IUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Remote {
    @Autowired
    private IUserService userService;

    @Autowired
    private static RedisUtils redisUtils;

    public static void RemoteReport(long lngDate) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = df.parse(df.format(new Date(lngDate)));
        } catch (ParseException e) {
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://taiyi_ecg.tjtzkt.com/submitInfo.aspx";
        Map<String, Object> map = new HashMap<>();
        map.put("key", "075b6eddd825148a674dfa8a8558ac62");
        String trans = restTemplate.getForObject(url, String.class, map);
        System.out.println(trans);
    }

    //调用post请求
    public static JSONObject sendPatAPI(String url, JSONObject header, JSONObject body) {

        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> formEntity = new HttpEntity<String>(body.toString(), headers);
        String re = client.postForObject(url, formEntity, String.class);
        JSONObject json = new JSONObject();
        System.out.println("result:" + re);
        if (StringUtil.isNotEmpty(re) || re.contains("success")) {
            json.put("result", "success");
            json.put("message", "患者信息传输成功");
            json.put("data", new JSONObject());
        } else if (StringUtil.isNotEmpty(re) || re.contains("exist")) {
            json.put("result", "exist");
            json.put("message", "患者信息已经存在！");
            json.put("data", new JSONObject());
        } else {
            json.put("result", "false");
            json.put("message", "患者信息传输错误");
            json.put("data", new JSONObject());
        }
        return json;
    }

    //调用post请求
    @SneakyThrows
    public static JSONObject callPostReportAPI(String url1, JSONObject header, JSONObject body) {
        String urlReport = "https://xdsj.oss-cn-beijing.aliyuncs.com/app/nap/singleBluetoothEcg/1ec229d4-5491-4e26-8618-79724a1da118_bp.pdf";
        String urlString = urlReport;

        HttpURLConnection url_con;
        String text = "";
        URL url;
        try {
            for (int i = 0; i < 1; i++) {
                url = new URL(urlString);
                url_con = (HttpURLConnection) url.openConnection();

                url_con.setRequestMethod("GET");
                url_con.setDoOutput(true);

                url_con.getOutputStream().flush();
                url_con.getOutputStream().close();
                InputStream in = url_con.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(in));

                FileOutputStream out = new FileOutputStream(new File("c://add8.pdf"));

                DataOutputStream dos = new DataOutputStream(out);
                String temp = new String();
                while (rd.read() != -1) {
                    temp = rd.readLine();
// dos.writeBytes(rd.readLine());
                    dos.write(rd.readLine().getBytes());
                }

            }
            System.out.println(text);
        } catch (Exception e) {
            try {
                System.out.println("exception occur" + e.toString());
            } catch (Exception ex) {
            }
        }


//        RestTemplate client = new RestTemplate();
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        //headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//
//        HttpEntity<String> formEntity = new HttpEntity<String>(body.toString(), headers);
//        String re= client.postForObject(url, formEntity, String.class);
//
//        JSONObject json = client.postForEntity(url, formEntity, JSONObject.class).getBody();

        //String obj = result.getBody();

        JSONObject json = null;
//        System.out.println("json:"+json.toString());
        return json;
    }

    /**
     * 从网络Url中下载文件
     *
     * @param urlReport
     * @param fileName
     * @param savePath
     * @throws IOException
     */
     public static void downLoadReoprtByUrl(String urlReport, String fileName, String savePath) throws IOException {
        URL url = new URL(urlReport);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        //设置超时间为3秒
        conn.setConnectTimeout(5 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        //文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }

        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }

        if (inputStream != null) {
            inputStream.close();
        }

        System.out.println("info:" + url + " download success");

    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];

        int len = 0;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);

        }

        bos.close();

        return bos.toByteArray();

    }


    /**
     * 不够位数的在前面补0，保留num的长度位数字
     * @param code 输入原始字符
     * @param num 输出字符串总长度
     * @return 前面补0后胡字符串
     */
    public static String autoGenericCode(String code, int num) {
        String result = "";
        // 保留num的位数
        // 0 代表前面补充0
        // num 代表长度为
        // d 代表参数为正数型
        result = String.format("%0" + num + "d", Integer.parseInt(code));
        return result;
    }


    public static void main(String[] args) {
        //==================================================================================================
        int randomNum = (int)((Math.random()*9+1)*100000); // 随机数 6 位
        //patid 为用户表id+6位随机数。
        String uid= "11";
        String patId= uid.concat("_").concat(""+randomNum);
        String patIdFileName=patId+".pdf";
        String createTime = DateUtil.parseStr(new Date(), "yyyy-MM-dd HH:mm:ss");
        String pdTime = DateUtil.parseStr(new Date(), "yyyy-MM-dd HH:mm:ss");



        String url = "http://taiyi_ecg.tjtzkt.com/submitInfo.aspx";
        JSONObject jsonBody= new JSONObject();
        jsonBody.put("orgid","32c43dd8-5994-4bff-84be-395653fc8e09");
        //jsonBody.put("patientId","8k870107-e37b-4330-b201-4d796cebee03");
        jsonBody.put("patientId",patId);
        jsonBody.put("patientName","孟庆华");
        jsonBody.put("birthday","1969-03-26");
        jsonBody.put("sex","男");
        jsonBody.put("CreateDate",createTime);
        jsonBody.put("pdTime",pdTime);
        jsonBody.put("dataType","动态血压");
        jsonBody.put("deviceMac","867717049684931");

        //测试
        //sendPatAPI(url,new JSONObject(),jsonBody);

         //写关系
         //orgid,doctor,uid,patientId,reportUrl


        //前缀+patientid.pdf
        String urlReport = "https://xdsj.oss-cn-beijing.aliyuncs.com/app/nap/singleBluetoothEcg/1ec229d4-5491-4e26-8618-79724a1da118_bp.pdf";
        JSONObject jsonHeader= new JSONObject();

        try {
            Remote.downLoadReoprtByUrl(urlReport, patIdFileName, RemoteConfig.reportLcoalPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
//=============================================================================================================

//        RestTemplate restTemplate = new RestTemplate();
//        //方法一：getForEntity(String var1, Class<T> var2)，没有参数
//        String url = "https://restapi.amap.com/v3/ip?key=075b6eddd825148a674dfa8a8558ac62";
//        String trans = restTemplate.getForObject(url,String.class);
//        System.out.println(trans);
//
//        //方法一：getForEntity(String var1, Class<T> var2, Object... var3)，url中用占位符，传入参数
//        //该方法提供了三个参数，其中var1为请求的地址(即url)，var2为请求响应body的包装类型，var3为url中的参数绑定
//        url = "https://restapi.amap.com/v3/ip?key={?}";
//        trans = restTemplate.getForObject(url,String.class,"075b6eddd825148a674dfa8a8558ac62");
//        System.out.println(trans);
//
//        //方法二：getForEntity(String var1, Class<T> var2, Map<String, ?> var3)，map传参
//        url = "https://restapi.amap.com/v3/ip?key={key}";
//        Map<String,Object> map = new HashMap<>();
//        map.put("key","075b6eddd825148a674dfa8a8558ac62");
//        trans = restTemplate.getForObject(url,String.class,map);
//        System.out.println(trans);
//
//        //方法三：getForEntity(URI var1, Class<T> var2)，uri传参
//        URI uri = URI.create("https://restapi.amap.com/v3/ip?key=075b6eddd825148a674dfa8a8558ac62");
//        trans = restTemplate.getForObject(uri,String.class);
//        System.out.println(trans);

        // 从redis取出数据，操作完，再设置（不用查询数据库）
        String json = redisUtils.get(Constants.FILES_KEY);
        //stringRedisTemplate.opsForSet().add("ddddd","hello");
        //stringRedisTemplate.opsForHash().put("ddd","1111","ggg");
        //stringRedisTemplate.delete(key);
    }

    /**
     * 发送动态血压用户数据
     * RemoteConfig.patReportUrl
     * @return
     */
    public Result updatePrescription(){
        //以下部分数据来源于
        SysUserEntity user = userService.getById("229"); // 首先获取用户表所有信息
        //patid 为用户表id+6位随机数。
        //int randomNum = (int) ((Math.random() * 9 + 1) * 100000); // 随机数 6 位
        //String patId= ruser.getId()+"".concat("_").concat(""+randomNum);
        String patId = "8k870107-e37b-4330-b201-002229764685";
//        String patId= user.getId()+"".concat("_").concat(""+randomNum);
        String patIdPortName = patId + "_bp.pdf";
        String createTime = DateUtil.parseStr(new Date(), "yyyy-MM-dd HH:mm:ss");
        String pdTime = DateUtil.parseStr(new Date(), "yyyy-MM-dd HH:mm:ss");

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("orgid", "e987ccfd-4f40-4128-9aed-7e9cde9706f1");
        jsonBody.put("patientId", patId);
        jsonBody.put("patientName", user.getNickName());
        if (ObjectUtil.isNotEmpty(user.getCardid())) {
            jsonBody.put("birthday", "1952-10-08");
        }
        jsonBody.put("sex", ObjectUtil.equals(user.getGender(), 1) ? "男" : "女");
//        jsonBody.put("CreateDate", createTime);
//        jsonBody.put("pdTime", pdTime);2022-09-06 10:41:02
        jsonBody.put("CreateDate", "2022-09-06 10:41:02");
        jsonBody.put("pdTime", "2022-09-06 10:41:02");
        jsonBody.put("dataType", "动态血压");
        jsonBody.put("analysisType", "0");
        //userDevice.getDeviceid(); 根据患者id获取绑定设备的编码
        jsonBody.put("deviceMac", "861831046819260");
        System.out.println("1----  "+jsonBody.toJSONString());
        JSONObject jsonRe= Remote.sendPatAPI(RemoteConfig.patReportUrl,new JSONObject(),jsonBody);

        System.out.println("2----  "+jsonRe.toJSONString());
        return Result.success();
    }
}